//
//  StatusListViewModel.swift
//  Sina
//
//  Created by 王杰 on 15/11/18.
//  Copyright © 2015年 王杰. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
import SDWebImage

class StatusListViewModel: NSObject {
    //MARK: 加载微博首页数据
    class func loadData(since_id since_id: Int,max_id: Int,finished: (array: [Status]?) -> ()) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        guard let token = UserAccountViewModel().token else {
            SVProgressHUD.showErrorWithStatus("您暂未登陆")
            return
        }
        
        var parameters = ["access_token": token]
        
        if since_id > 0 {
        //添加since_id 对应键值
        parameters["since_id"] = "\(since_id)"
        
        }
        //	若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
        if max_id > 0 {
            parameters["max_id"] = "\(max_id - 1)"
        }

        //执行网络回调
        NetworkTools.sharedTools.requestJsonDict(.GET, urlString: urlString, parmaters: parameters) { (result, error) -> () in
            if error != nil {
                //错误回调
                finished(array: nil)
                return
            }
            if let array = result!["statuses"] as? [[String : AnyObject]] {
                
                var list = [Status]()
                //遍历数组
                for item in array {
                    //字典转模型
                    let s = Status(dict: item)
                    //添加微博对象
                    list.append(s)
                }
                //完成单张图片的缓存
                StatusListViewModel.cacheStatusImage(list, finished: finished)
                
            }
            
        }
    }
    private class func cacheStatusImage(array: [Status],finished: (array: [Status]?) -> ()) {
        
        //缓存单张图片
        if array.count == 0 {
            finished(array: nil)
            return
        }
        //创建群组
        let group = dispatch_group_create()
        //遍历模型数组
        for s in array {
            if let imageurls = s.pictureURLs {
                
                if imageurls.count != 1 {
                    continue
                }
                //一定是单张图片
                for url in imageurls {
                    //开始下载异步加载图片的开始向群组中添加异步任务
                    dispatch_group_enter(group)
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                        print("单张图片下载完成")
                        //异步任务离开群组
                        dispatch_group_leave(group)
                    })
                }
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            //在主线程完成回调
            print("所有的异步图片下载完成")
            finished(array: array)
        }
        
    }
}

